package com.idp.web.shop.controller;
import com.idp.web.shop.entity.Goods;
import com.idp.web.shop.service.GoodsService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.idp.common.base.BaseController;
import com.idp.common.model.Response;
import com.idp.common.persistence.Page;
import com.idp.common.util.ValidateUtils;

/**
 * 商品信息controller
 * @author WuJiangWu
 * @date 2018年4月21日下午8:32:11
 */
@Controller
@RequestMapping("/goods")
public class GoodsController extends BaseController {

	private Logger logger = Logger.getLogger(GoodsController.class);

	@Resource
	private GoodsService goodsService;
	
	/**
	 * 	2018-04-12 WuJiangWu
	 * 	初始化查询页面
	 * @return
	 */
	@RequestMapping("/init")
	public String init(){
		
		return "shop/goods/goodsSearch";
	}
	
	/**
	 * 	2018-04-12 WuJiangWu
	 * 	分页查询
	 * @param goods
	 * @param page
	 * @param request
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Goods goods,Page<Goods> page,HttpServletRequest request){
		try {
			request.setAttribute("page", goodsService.findByPage(goods, page));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "shop/goods/goodsList";
	}

	/**
	 * 	2018-04-12 WuJiangWu
	 * 	新增修改页面初始化
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/goods")
	public String goods(String id,HttpServletRequest request){
		try {
			if(ValidateUtils.isNotEmpty(id)){
				
				Goods goods = goodsService.getById(id);
				request.setAttribute("goods", goods);
			}
		} catch (Exception e) {
			
			logger.error(e.getMessage(), e);
		}
		return "shop/goods/goods";
	}
	
	/**
	 * 	2018-04-12 WuJiangWu
	 * 	保存
	 * @param goods
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Response save(Goods goods){
		Response json = new Response();
		try {
			// 修改
			if(ValidateUtils.isNotEmpty(goods.getId())){
				goodsService.update(goods);
			}
			// 新增
			else{
				goodsService.add(goods);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			json.setErrcode(-1);
			json.setMsg("保存失败");
		}
		return json;
	}
	
	/**
	 * 	2018-04-12 WuJiangWu
	 * 	删除
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Response delete(String id){
		Response json = new Response();
		try {
			goodsService.delete(id);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			json.setErrcode(-1);
			json.setMsg("删除失败");
		}
		return json;
	}
}
